//
//  AirContentScrollView.m
//  YSSmartHome
//
//  Created by yanghao on 2017/3/14.
//  Copyright © 2017年 yahaong. All rights reserved.
//

#import "AirContentScrollView.h"
#import "YSCommon.h"
#import "WaveView.h"
#import "AirAttributedView.h"
#import "ZTAirRecordButton.h"
#import "ZTAirButton.h"
#import "PNChart.h"
#import "ZTAirChartView.h"
#import "CommonUtils.h"
@interface AirContentScrollView ()
<
UIScrollViewDelegate
>
@property (nonatomic, nonatomic, strong) UIView* mContentView;

@property (nullable, nonatomic, strong) UIView* mTopContentView;
@property (nullable, nonatomic, strong) UIImageView* mImgCircle;
@property (nullable, nonatomic, strong) WaveView* wave;
@property (nullable, nonatomic, strong) AirAttributedView* mAirAttributedView;
@property (nullable, nonatomic, strong) ZTAirRecordButton* mBtnRecord;

@property (nullable, nonatomic, strong) ZTAirButton* mBtnLastday;
@property (nullable, nonatomic, strong) ZTAirButton* mBtnLastWeak;
@property (nullable, nonatomic, strong) ZTAirButton* mBtnLastMouth;

@property (nullable, nonatomic, strong) UIScrollView* mChartScrollView;
@property (nullable, nonatomic, strong) UIView* mChartContentView;
@property (nullable, nonatomic, strong) ZTAirChartView* pmChartView;
@property (nullable, nonatomic, strong) ZTAirChartView* formaldehydeChartView;
@property (nullable, nonatomic, strong) ZTAirChartView* tempChartView;

@property (atomic, assign) BOOL isAnimation;
@end
@implementation AirContentScrollView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initSubviews];
        
        UITapGestureRecognizer* tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTappedWave)];
        [self.wave addGestureRecognizer:tapGes];
        
        self.delegate = self;
        self.mChartScrollView.delegate = self;
        
    }
    return self;
}


#pragma mark - event response 

- (void)recordBtnTapped
{
    
}
- (void)didTappedWave
{
    __weak typeof(self)wself = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __strong typeof(wself)sself = wself;
        [sself sendAirData:!sself.device.isSendAirDataEnable];
    });
    

}
#pragma mark - UITableViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    BOOL isContent = (scrollView == self.mChartScrollView);
    if (isContent) {
        BOOL isScroll =  self.contentOffset.y < self.self.mBtnRecord.frame.origin.y;
        CGFloat offsetY = scrollView.contentOffset.y + self.contentOffset.y;
        NSLog(@"%f ---  %f",scrollView.contentOffset.y, self.contentOffset.y);
        if (isScroll) {
            [self setContentOffset:CGPointMake(0, offsetY)];
            [scrollView setContentOffset:CGPointZero];
        }
        else if(scrollView.contentOffset.y <= 0 && !isScroll)
        {
            if (self.contentOffset.y >= self.self.mBtnRecord.frame.origin.y) {
                [self setContentOffset:CGPointMake(0, offsetY)];
            }
        }
    }
    else if (scrollView == self)
    {
        NSLog(@"%f",self.contentOffset.y);
        if (self.contentOffset.y >= self.self.mBtnRecord.frame.origin.y) {
            [self setContentOffset:CGPointMake(0,  self.self.mBtnRecord.frame.origin.y)];
        }
    }
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    BOOL isContent = (scrollView == self.mChartScrollView);
    if (isContent) {
        CGFloat offsetY = self.contentOffset.y;
        if (offsetY < 0) {
            [self setContentOffset:CGPointZero
                                         animated:YES];
        }
    }
    
}

#pragma mark - private method
- (void)initSubviews
{
    self.backgroundColor = RGBColor(0, 111, 195);
    [self addSubview:self.mContentView];
    [self.mContentView addSubview:self.mTopContentView];
    [self.mTopContentView addSubview:self.mImgCircle];
    [self.mTopContentView addSubview:self.wave];
    [self.mTopContentView addSubview:self.mAirAttributedView];
    [self.mContentView addSubview:self.mBtnRecord];
    [self.mContentView addSubview:self.mBtnLastday];
    [self.mContentView addSubview:self.mBtnLastWeak];
    [self.mContentView addSubview:self.mBtnLastMouth];
    [self.mContentView addSubview:self.mChartScrollView];
    [self.mChartScrollView addSubview:self.mChartContentView];
    [self.mChartContentView addSubview:self.pmChartView];
    [self.mChartContentView addSubview:self.formaldehydeChartView];
    [self.mChartContentView addSubview:self.tempChartView];
    [self layoutPageSubViews];
    
}

- (void)layoutPageSubViews
{
    [self.mContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [self.mTopContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.mContentView);
        make.height.equalTo(kScreenHeight - 64 - kIphoneSize_Height(53));
    }];
    [self.mImgCircle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mTopContentView).offset(kIphoneSize_Height(30));
        make.centerX.equalTo(self.mTopContentView);
        make.width.height.equalTo(kIphoneSize_Widith(248));
    }];
    [self.wave mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.mImgCircle);
        make.width.height.equalTo(kIphoneSize_Widith(208));
    }];
    [self.mAirAttributedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mImgCircle.bottom).offset(kIphoneSize_Height(50));
        make.leading.trailing.equalTo(self.mTopContentView);
        make.height.equalTo(kIphoneSize_Height(219));
    }];
    [self.mBtnRecord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.mContentView);
        make.height.equalTo(kIphoneSize_Height(53));
        make.top.equalTo(self.mTopContentView.bottom);
    }];
    
    [self.mBtnLastday mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mBtnRecord.bottom);
        make.leading.equalTo(self.mContentView);
        make.height.equalTo(kIphoneSize_Height(44));
        make.width.equalTo(kScreenWidth / 3);
    }];
    [self.mBtnLastWeak mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.width.equalTo(self.mBtnLastday);
        make.leading.equalTo(self.mBtnLastday.trailing);
    }];
    [self.mBtnLastMouth mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.width.equalTo(self.mBtnLastday);
        make.leading.equalTo(self.mBtnLastWeak.trailing);
    }];
    
    

    [self.mChartScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.mContentView);
        make.top.equalTo(self.mBtnLastday.bottom);
        make.height.equalTo(kScreenHeight - kIphoneSize_Height(53) - 64 - kIphoneSize_Height(44));
    }];
    [self.mChartContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.mChartScrollView);
        make.width.equalTo(self.mChartScrollView );
    }];
    [self.pmChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.mChartContentView).offset(kIphoneSize_Widith(10));
        make.trailing.equalTo(self.mChartContentView).offset(kIphoneSize_Widith(-10));
        make.top.equalTo(self.mChartContentView);
        make.height.equalTo(kIphoneSize_Height(185));
    }];
    [self.formaldehydeChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.height.leading.equalTo(self.pmChartView);
        make.top.equalTo(self.pmChartView.bottom).offset(kIphoneSize_Height(20));
    }];
    [self.tempChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.height.leading.equalTo(self.formaldehydeChartView);
        make.top.equalTo(self.formaldehydeChartView.bottom).offset(kIphoneSize_Height(20));
    }];
    [self.mChartContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.tempChartView);
    }];
    [self.mContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self);
        make.bottom.equalTo(self.mChartScrollView.bottom);
    }];
    
}


- (void)startCircleRotation:(UIView*)view
{
    CABasicAnimation* rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotateAnimation.repeatCount = MAXFLOAT;
    rotateAnimation.toValue = @(-2*M_PI) ;
    rotateAnimation.duration = 2.5;
    rotateAnimation.cumulative = YES;
    rotateAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    rotateAnimation.removedOnCompletion = NO;
    rotateAnimation.fillMode = kCAFillModeForwards;
    [view.layer addAnimation:rotateAnimation forKey:@"circle"];
    self.isAnimation = YES;
}

- (void)stopCircleRotation:(UIView*)view
{
    [view.layer removeAnimationForKey:@"circle"];
    self.isAnimation = NO;
}


- (void)sendAirData:(BOOL)isEnable
{
    XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_BOOL bytes:&isEnable length:sizeof(isEnable)];
    [kMQTTSessionManager.xai sendCMD:0x01 toApsn:self.device.apsn toLuid:self.device.luid datas:@[tlv]];
}

#pragma mark - getters and setters

- (void)setDevice:(ZTAirMonitorDevice *)device
{
    _device = device;
    if (device.isSendAirDataEnable &&!self.isAnimation) {
        [self stopCircleRotation:self.mImgCircle];
        [self startCircleRotation:self.mImgCircle];
    }
    else if (!device.isSendAirDataEnable && self.isAnimation)
    {
        [self stopCircleRotation:self.mImgCircle];
    }
    self.wave.value = device.pmValue;
    self.mAirAttributedView.device  = device;
    
    int colorHex = [CommonUtils evaluateColor:0xFF006fc3 endValue:0xFFef4b3a fraction: device.pmValue / 500.0];
    self.backgroundColor = UIColorFromHex(colorHex);
   
}

- (void)setPmArray:(NSArray *)pmArray
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _pmArray = pmArray;
        self.pmChartView.xlables = pmArray;
    });
}

- (void)setFormaldehydeArray:(NSArray *)formaldehydeArray
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _formaldehydeArray = formaldehydeArray;
        self.formaldehydeChartView.xlables = _formaldehydeArray;
    });
}
- (void)setTempArray:(NSArray *)tempArray
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _tempArray = tempArray;
        self.tempChartView.xlables = _tempArray;
    });
}
- (UIView *)mContentView
{
    if (!_mContentView) {
        _mContentView = [[UIView alloc]init];
    }
    return _mContentView;
}

- (UIView *)mTopContentView
{
    if (!_mTopContentView) {
        _mTopContentView = [[UIView alloc]init];
    }
    return _mTopContentView;
}
- (UIImageView *)mImgCircle
{
    if (!_mImgCircle) {
        _mImgCircle = [[UIImageView alloc]init];
        _mImgCircle.image = [UIImage imageNamed:@"新设备-空气检测器1"];
        
    }
    return _mImgCircle;
}

- (AirAttributedView *)mAirAttributedView
{
    if (!_mAirAttributedView) {
        _mAirAttributedView = [[AirAttributedView alloc]init];
    }
    return _mAirAttributedView;
}
- (ZTAirRecordButton *)mBtnRecord
{
    if (!_mBtnRecord) {
        _mBtnRecord = [[ZTAirRecordButton alloc]initWithTitle:@"检测记录" imageName:@"新设备-空气检测器3-上滑"];
        [_mBtnRecord addTarget:self action:@selector(recordBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    }
    return _mBtnRecord;
    
}
- (WaveView *)wave
{
    if (!_wave) {
        _wave = [[WaveView alloc]init];
    }
    return _wave;
}

- (ZTAirChartView *)pmChartView
{
    if (!_pmChartView) {
        _pmChartView = [[ZTAirChartView alloc]initWithXlabels:@[@"3:00",@"6:00",@"9:00",@"12:00",@"15:00",@"18:00",@"21:00",@"24:00"] block:nil];
        _pmChartView.topBackgroundImage = [UIImage imageNamed:@"pm_top_background"];
        _pmChartView.title = @"PM";
    }
    return _pmChartView;
}
- (ZTAirChartView *)formaldehydeChartView
{
    if (!_formaldehydeChartView) {
        _formaldehydeChartView = [[ZTAirChartView alloc]initWithXlabels:@[@"3:00",@"6:00",@"9:00",@"12:00",@"15:00",@"18:00",@"21:00",@"24:00"]block:^NSString * _Nullable(CGFloat value) {
            return [NSString stringWithFormat:@"%.3f",value / 1000 * 0.833];
        }];

        _formaldehydeChartView.topBackgroundImage = [UIImage imageNamed:@"formaldehyde_top_background"];
        _formaldehydeChartView.title = @"甲醛";
    }
    return _formaldehydeChartView;
}
- (ZTAirChartView *)tempChartView
{
    if (!_tempChartView) {
        _tempChartView = [[ZTAirChartView alloc]initWithXlabels:@[@"3:00",@"6:00",@"9:00",@"12:00",@"15:00",@"18:00",@"21:00",@"24:00"]block:^NSString * _Nullable(CGFloat value) {
            return [NSString stringWithFormat:@"%.1f",value / 10.0];
        }];

        _tempChartView.topBackgroundImage = [UIImage imageNamed:@"temp_top_background"];
        _tempChartView.title = @"温度";
    }
    return _tempChartView;
}

- (ZTAirButton *)mBtnLastday
{
    if (!_mBtnLastday) {
        _mBtnLastday = [[ZTAirButton alloc]init];
        [_mBtnLastday setImage:[UIImage imageNamed:@"新设备-空气检测器4-选择"] forState:UIControlStateNormal];
        [_mBtnLastday setTitle:@"最近一天" forState:UIControlStateNormal];
    }
    return _mBtnLastday;
}
- (ZTAirButton *)mBtnLastWeak
{
    if (!_mBtnLastWeak) {
        _mBtnLastWeak = [[ZTAirButton alloc]init];
        [_mBtnLastWeak setImage:[UIImage imageNamed:@"新设备-空气检测器4-选择"] forState:UIControlStateNormal];
        [_mBtnLastWeak setTitle:@"最近一周" forState:UIControlStateNormal];
    }
    return _mBtnLastWeak;
}
- (ZTAirButton *)mBtnLastMouth
{
    if (!_mBtnLastMouth) {
        _mBtnLastMouth = [[ZTAirButton alloc]init];
        [_mBtnLastMouth setImage:[UIImage imageNamed:@"新设备-空气检测器4-选择"] forState:UIControlStateNormal];
        [_mBtnLastMouth setTitle:@"最近一月" forState:UIControlStateNormal];
    }
    return _mBtnLastMouth;
}
- (UIScrollView *)mChartScrollView
{
    if (!_mChartScrollView) {
        _mChartScrollView = [[UIScrollView alloc]init];
        _mChartScrollView.showsVerticalScrollIndicator = NO;
        _mChartScrollView.showsHorizontalScrollIndicator = NO;
    }
    return _mChartScrollView;
}
- (UIView *)mChartContentView
{
    if (!_mChartContentView) {
        _mChartContentView = [[UIView alloc]init];
    }
    return _mChartContentView;
}

@end
